//
//  V2NotificationViewController.m
//  v2ex-iOS
//
//  Created by Singro on 4/5/14.
//  Copyright (c) 2014 Singro. All rights reserved.
//

#import "JrdSettingsViewController.h"
#import "JrdCommon.h"
#import "UIColor+JRDNote.h"
#import "CLDownloadRequest.h"
#import "LCCSqliteManager.h"
#import "JrdDatamanager.h"
#define SETTINGS_MANAGE_DOWNLOAD 0
#define SETTINGS_DOWNLOAD_WITH_WIFI 1
#define SETTINGS_CURRENT_VERSION 2
#define SETTINGS_DELETE_CACHE 3

@interface JrdSettingsViewController () <UITableViewDataSource, UITableViewDelegate, UIViewControllerPreviewingDelegate, UIAlertViewDelegate>{
    LCCSqliteManager* manager;
}

@property (nonatomic, assign) NSInteger pageCount;

@property (nonatomic, copy) void (^getNotificationListBlock)(NSUInteger page);

@property (nonatomic, strong) SCBarButtonItem *leftBarItem;
@property(strong, nonatomic) UISwitch *swichView;

@end

@implementation JrdSettingsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

        self.pageCount = 1;
        
    }
    return self;
}

- (void)loadView {
    [super loadView];
    [self initView];
    [self configureTableView];
    [self configureNavibarItems];
    
}
- (void)initView{
    CGRect cellFrame = CGRectMake(self.view.width - 100, 10, 40, 40);
    
    _swichView = [[UISwitch alloc] initWithFrame:cellFrame];
    _swichView.onImage = [UIImage imageNamed:@"switch_on.png"];
    _swichView.offImage = [UIImage imageNamed:@"switch_off.png"];
    if([[NSUserDefaults standardUserDefaults] boolForKey:@"vDownloadUnderWifi"] == YES){
        [_swichView setOn:YES];
    }else{
        [_swichView setOn:FALSE];
    }
    _swichView.layer.masksToBounds = YES;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.sc_navigationItem.leftBarButtonItem = self.leftBarItem;
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reloadData)
                                                 name:kUpdateDownloadInfoNotification
                                               object:nil];
    manager = [LCCSqliteManager shareInstance];
    //[manager openSqliteFile:@"database"];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    //init navigation title and background color
    self.sc_navigationItem.title = NSLocalizedString(@"v2_settings",nil);//@"我们学习";
    [self.tableView reloadData];
}

#pragma mark - Layout

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    self.hiddenEnabled = YES;
    
}

#pragma mark - Configure Views & blocks

- (void)configureNavibarItems {
    self.leftBarItem = [[SCBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ico-menu"] highlight:[UIImage imageNamed:@"ico-menu"] style:SCBarButtonItemStylePlain handler:^(id sender) {
        [[NSNotificationCenter defaultCenter] postNotificationName:kShowMenuNotification object:nil];
    }];
    
}

- (void)configureTableView {
    
    self.tableView                 = [[UITableView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - (NAVIGATION_BAR_HEIGHT))];
    self.tableView.separatorStyle  = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate        = self;
    self.tableView.dataSource      = self;
    [self.view addSubview:self.tableView];
    
}
#pragma mark - Setters


#pragma mark - TableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return V2_SETTING_TABLE_COUNT;//self.notificationList.list.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return JRD_TABLE_CELL_HEIGHT;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    }
    
    if(0 == indexPath.row){
        UIView *headerLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.5)];
        headerLineView.backgroundColor = JrdSpeLineColor;
        [cell addSubview:headerLineView];

    }
    
    UIFont *myFont = [UIFont fontWithName:@"HelveticaNeue-Light" size:17.0];
    cell.textLabel.font = myFont;
    [cell.textLabel setTextColor:[UIColor blackColor]];
    cell.detailTextLabel.font = myFont;
    cell.detailTextLabel.textColor =Jrd9BColor;// [UIColor JRDColorStandardBlue];
    switch (indexPath.row) {
        case  SETTINGS_MANAGE_DOWNLOAD:
        {
            cell.textLabel.text = NSLocalizedString(@"v2_manage_download", nil);//@"Change Photo";
            NSString* docsDir = [self downLoadFilePath];
            NSString *savePath = [docsDir stringByAppendingPathComponent:@"CLDownload"];

           // NSString* filepath = [CLDownloadRequest downloadPath];
            float size = [self fileSizeForDir:savePath];
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%.1fM",size];
        }
        break;
        case  SETTINGS_DOWNLOAD_WITH_WIFI:
        {
            cell.textLabel.text = NSLocalizedString(@"v2_download_when_wifi", nil);//@"Change Photo";
            
            [self.swichView addTarget:self action:@selector(switchHandler) forControlEvents:UIControlEventTouchUpInside];
            cell.accessoryView = self.swichView;

        }
            break;
        case  SETTINGS_CURRENT_VERSION:
        {
            NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
            // app版本
            NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
            cell.textLabel.text = NSLocalizedString(@"v2_current_version", nil);//@"Change Photo";
            cell.detailTextLabel.text  = app_Version;//@"2.3.4";
        }
            break;
        case  SETTINGS_DELETE_CACHE:
        {
            cell.textLabel.text = NSLocalizedString(@"v2_delete_cache", nil);//@"Change Photo";
        }
            break;
    }
    [cell.layer setMasksToBounds:YES];
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(10, (JRD_TABLE_CELL_HEIGHT - 0.5), SCREEN_WIDTH - 10, 0.5)];
    lineView.backgroundColor = JrdSpeLineColor;
    [cell addSubview:lineView];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(SETTINGS_DELETE_CACHE == indexPath.row)
    {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:nil message:NSLocalizedString(@"jrd_delete_cache_alert", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"jrd_cancel", nil) otherButtonTitles:NSLocalizedString(@"jrd_done", nil) , nil];
        [alert show];
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(1 == buttonIndex){
        //清空下载文件夹
        NSFileManager * fileManager = [[NSFileManager alloc]init];
        NSString* savePath = [self downLoadFilePath];
        [fileManager removeItemAtPath:[NSString stringWithFormat:@"%@/CLDownload",savePath] error:nil];
        [self updateDB];
        [self.tableView reloadData];
    }else{
        NSString* path = [self downLoadFilePath];
        NSLog(@"%@", path);
    }
}

- (void)updateDB{
    //update data
    //search all is download value from courselist
    dispatch_async(dispatch_get_main_queue(), ^{

    NSString * searchCondition = [NSString stringWithFormat:@"is_operated=%@ and user_id=%@",
                                  @(1),[JrdDatamanager manager].user.userId];
    NSArray* courseSel= [manager searchDataFromSheet:@"courselist" where:searchCondition];
    for(int i = 0; i < courseSel.count;  i++){
        NSString * searchConditionExt = [NSString stringWithFormat:@"course_id=%@ and user_id=%@",
                                         courseSel[i][COURSE_ID],[JrdDatamanager manager].user.userId];

        Boolean retExt = [manager updateDataToSheet_couse_download:@"courselist" withData:@[@(0)] where:searchConditionExt];
        NSLog(@"ret = %d", retExt);
    }

    NSString * searchCondition_node = [NSString stringWithFormat:@"is_download=%@ and user_id=%@",
                                  @(1),[JrdDatamanager manager].user.userId];
    NSArray* nodeListData= [manager searchDataFromSheet:@"nodelist" where:searchCondition_node];
    for(int i = 0; i < nodeListData.count;  i++){
        NSString * searchCondition_updateNode = [NSString stringWithFormat:@"node_id=%@ and user_id=%@",
                                      nodeListData[i][NODE_ID],[JrdDatamanager manager].user.userId];
        Boolean ret = [manager updateDataToSheet_DownloadUrl:@"nodelist" withData:@[@(0), @""] where:searchCondition_updateNode];
        NSLog(@"ret = %d", ret);

    }
    [[NSNotificationCenter defaultCenter] postNotificationName:kDeleteCacheNotification object:self];

    });
}
#pragma mark - Configure TableCell

#pragma mark - Preview


#pragma mark - Nofitications

- (void)didReceiveUpdateCheckInBadgeNotification {
    
    /*if ([V2CheckInManager manager].isExpired && kSetting.checkInNotiticationOn) {
        self.leftBarItem.badge = @"";
    } else {
        self.leftBarItem.badge = nil;
    }*/
    
}

#pragma mark - switchhandler
- (void)switchHandler{
    //BOOL isOn = _swichView.on;
    if(YES == _swichView.on){
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"vDownloadUnderWifi"];
    }else{
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"vDownloadUnderWifi"];
    }
    // switch handler function
    NSLog(@"switch handler");
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 5;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView* headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.size.width, 10)];
    headerView.backgroundColor = JrdTableHeadColor;//[UIColor clearColor];
    return headerView;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section;   // custom view for footer. will be adjusted to default or specified footer height
{
    UIView* footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.size.width, 5)];
    footView.backgroundColor = [UIColor clearColor];
    return footView;

}



-(float)fileSizeForDir:(NSString*)path//计算文件夹下文件的总大小
{
    
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    float size =0;
    NSArray* array = [fileManager contentsOfDirectoryAtPath:path error:nil];
    for(int i = 0; i<[array count]; i++)
    {
        NSString *fullPath = [path stringByAppendingPathComponent:[array objectAtIndex:i]];
        
        BOOL isDir;
        if ( !([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && isDir) )
        {
            NSDictionary *fileAttributeDic=[fileManager attributesOfItemAtPath:fullPath error:nil];
            size+= fileAttributeDic.fileSize/ 1024.0/1024.0;
        }
        else
        {
            [self fileSizeForDir:fullPath];
        }
    }
    //han = han + size;
    return size;
}

-(NSString*)downLoadFilePath{

    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docsDir = [documentPaths objectAtIndex:0];
    return docsDir;
}


- (void)reloadData{
    [self.tableView reloadData];
}

@end
